#include "NewDownloadDialog.h"
#include <QHBoxLayout>
#include <QFileDialog>
#include <QFormLayout>
#include <QSpinBox>
#include <QDebug>

NewDownloadDialog::NewDownloadDialog(QWidget *parent) :
	QDialog(parent)
{
	downloadLink = new QLineEdit(this);
	connect(downloadLink, SIGNAL(textChanged(QString)), this, SLOT(checkInput()));

	savingPath = new QLineEdit(this);
	connect(savingPath, SIGNAL(textChanged(QString)), this, SLOT(checkInput()));

	QPushButton *searchSavingPathButton = new QPushButton("Search", this);
	connect(searchSavingPathButton, SIGNAL(clicked()), this, SLOT(searchSavingPath()));

	okButton = new QPushButton("Ok", this);
	okButton->setEnabled(false);
	connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));

	QPushButton *cancelButton = new QPushButton("Cancel", this);
	connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));

	priorityChooser = new PrioritySpinBox;
	connect(priorityChooser, SIGNAL(valueChanged(int)), this, SLOT(checkInput()));

	QHBoxLayout *savingPathLayout = new QHBoxLayout;
	savingPathLayout->addWidget(savingPath);
	savingPathLayout->addWidget(searchSavingPathButton);

	QHBoxLayout *buttonsLayout = new QHBoxLayout;
	buttonsLayout->addStretch();
	buttonsLayout->addWidget(okButton);
	buttonsLayout->addWidget(cancelButton);


	QFormLayout *mainLayout = new QFormLayout;
	mainLayout->addRow("Download from:", downloadLink);
	mainLayout->addRow("Save to:", savingPathLayout);
	mainLayout->addRow("Priority:", priorityChooser);
	mainLayout->addRow(buttonsLayout);

	setLayout(mainLayout);
	setModal(true);
	setFixedSize(400, 150);
}

QString NewDownloadDialog::getDownloadLink() const
{
	return downloadLink->text();
}

QString NewDownloadDialog::getSavingPath() const
{
	return savingPath->text();
}

int NewDownloadDialog::getPriority() const
{
	return priorityChooser->value();
}


void NewDownloadDialog::searchSavingPath()
{
	QFileDialog *fileDialog = new QFileDialog();
	fileDialog->setAcceptMode(QFileDialog::AcceptSave);
	fileDialog->setFileMode(QFileDialog::DirectoryOnly);

	if (fileDialog->exec() == QFileDialog::Accepted &&
		!fileDialog->selectedFiles().isEmpty()) {
		savingPath->setText(fileDialog->selectedFiles()[0]);
	}
}

void NewDownloadDialog::checkInput()
{
	if (downloadLink->text().trimmed().isEmpty() ||
		savingPath->text().trimmed().isEmpty() ||
		!priorityChooser->hasAcceptableInput()) {
		okButton->setEnabled(false);
	} else {
		okButton->setEnabled(true);
	}
}
